<?php

namespace app\api\controller\v2;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Channels;
use app\admin\model\cms\RatingModel;
use app\admin\model\cms\VideoCategoryModel;
use app\api\service\cms\CacheService;
use app\common\controller\Api;
use app\common\model\UserFavorite;
use think\Model;

/**
 * 视频相关接口
 */
class Video extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = [''];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!\think\Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //获取视频推荐列表 每日/每周/推荐-增加了redis缓存,但是效果不如原来的,暂时不用
    public function getVideoList_cache()
    {
        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $type = $request['type'] ?? 1;//1:每日,2:每周,3:推荐
        switch ($type) {
            case 1:
                $video_category_id = 13;//每天听复盘
                break;
            case 2:
                $video_category_id = 12;//每周债市复盘
                break;
            case 3:
                $limit = 10;
                break;
            default:
                $this->error('type类型不正确');
        }
        //操作缓存
        $cache_service = new CacheService();

        $top_data_id = \app\admin\model\cms\Video::where('type', 1);
        if ($type != 3) {
            $top_data_id = $top_data_id->where('video_category_id', $video_category_id);
        } else {
            $top_data_id = $top_data_id->where('is_recommend', 1);
        }
        $top_data_id = $top_data_id->order('is_top', 'desc')
            ->order('sort', 'desc')
            ->order('id', 'desc')
            ->value('id');
        $top_data = $cache_service->showHashData('video',$top_data_id);

        $data_arr = \app\admin\model\cms\Video::field('id,video_category_id,image,video_path')->where('type', 1);
        if ($top_data) {
            $data_arr = $data_arr->where('id', '<>', $top_data['id']);
        }
        if ($type != 3) {
            $data_arr = $data_arr->where('video_category_id', $video_category_id);
        } else {
            $data_arr = $data_arr->where('is_recommend', 1);
        }
        $data_arr = $data_arr->order('sort', 'desc')->order('id', 'desc')->paginate($limit, false, ['page' => $page])->toArray();

        if ($top_data) {
            if ($top_data['user']['avatar'] ?? null) {
                if (substr($top_data['user']['avatar'], 0, 1) === '/') {
                    $top_data['user']['avatar'] = obsurl($top_data['user']['avatar']);
                }
            }
            if ($top_data['image']) {
                if (substr($top_data['image'], 0, 1) === '/') {
                    $top_data['image'] = obsurl($top_data['image']);
                }
            }
            unset($top_data['video_path'], $top_data['video_path_obs']);

            //检测用户是否有权访问内容
            $top_data['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $top_data['id'], $top_data['video_category_id']);//检测用户是否购买相关内容会员
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $top_data['is_member_expire'] = 1;
            }
        }

        foreach ($data_arr['data'] as $k => &$v) {
            $v = $cache_service->showHashData('video',$v['id']);
            //检测用户是否有权访问内容
            $v['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $v['id'], $v['video_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $v['is_member_expire'] = 1;
            }

            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            unset($v['video_path'], $v['video_path_obs']);
            if ($v['user']['avatar'] ?? null) {
                if (substr($v['user']['avatar'], 0, 1) === '/') {
                    $v['user']['avatar'] = obsurl($v['user']['avatar']);
                }
            }
        }

        $res = [
            'top_data' => $top_data ?: [],
            'list_data' => $data_arr['data'],
        ];

        $this->success('', $res);
    }

    //获取视频推荐列表 每日/每周/推荐
    public function getVideoList()
    {
        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $type = $request['type'] ?? 1;//1:每日,2:每周,3:推荐
        switch ($type) {
            case 1:
                $video_category_id = 13;//每天听复盘
                break;
            case 2:
                $video_category_id = 12;//每周债市复盘
                break;
            case 3:
                $limit = 10;//推荐视频
                break;
            default:
                $this->error('type类型不正确');
        }

        $top_data = \app\admin\model\cms\Video::field('id,title,image,video_path,user_id,video_category_id')
            ->with(['user'])
            ->where('type', 1);
        if ($type != 3) {
            $top_data = $top_data->where('video_category_id', $video_category_id);
        } else {
            $top_data = $top_data->where('is_recommend', 1);//是否推荐到首页|默认0:否,1:是
        }

        $top_data = $top_data->order('is_top', 'desc')
            ->order('id', 'desc')
            ->find();

        $data_arr = \app\admin\model\cms\Video::field('id,title,image,video_path,video_category_id,user_id,video_category_id')
            ->with(['user'])
            ->where('type', 1);
        if ($top_data) {
            $data_arr = $data_arr->where('id', '<>', $top_data['id']);
        }

        if ($type != 3) {
            $data_arr = $data_arr->where('video_category_id', $video_category_id);
        } else {
            $data_arr = $data_arr->where('is_recommend', 1);
        }
        $data_arr = $data_arr->order('sort', 'desc')->order('id', 'desc')->paginate($limit, false, ['page' => $page])->toArray();

        if ($top_data) {
            $top_data = $top_data->toArray();
            if ($top_data['user']['avatar'] ?? null) {
                if (substr($top_data['user']['avatar'], 0, 1) === '/') {
                    $top_data['user']['avatar'] = obsurl($top_data['user']['avatar']);
                }
            }
            if ($top_data['image']) {
                if (substr($top_data['image'], 0, 1) === '/') {
                    $top_data['image'] = obsurl($top_data['image']);
                }
            }
            unset($top_data['video_path'], $top_data['video_path_obs']);

            //检测用户是否有权访问内容
            $top_data['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $top_data['id'], $top_data['video_category_id']);//检测用户是否购买相关内容会员
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $top_data['is_member_expire'] = 1;
            }
        }

        foreach ($data_arr['data'] as $k => &$v) {
            //检测用户是否有权访问内容
            $v['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $v['id'], $v['video_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $v['is_member_expire'] = 1;
            }

            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            unset($v['video_path'], $v['video_path_obs']);
            if ($v['user']['avatar'] ?? null) {
                if (substr($v['user']['avatar'], 0, 1) === '/') {
                    $v['user']['avatar'] = obsurl($v['user']['avatar']);
                }
            }
        }

        $res = [
            'top_data' => $top_data ?: [],
            'list_data' => $data_arr['data'],
        ];

        $this->success('', $res);
    }

    //增加观看视频积分
    public function addWatchVideoScore()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息

        $video_id = $request['id'];

        if (!$video_id) {
            $this->error('视频id不正确');
        }

        $video = \app\admin\model\cms\Video::where('id', $video_id)->find();
        if (!$video) {
            $this->error('视频信息不存在');
        }

        //增加相应积分
        $score = new Score();
        $editScore = $score->editScore($user['id'], $video['id'], 'watch_video_score', 1, 'video');//调整积分-观看视频
        if ($editScore['code'] != 200) {
            $this->error('获取积分已达上限');
        }
        $this->success('积分添加成功');
    }

    //获取当前专辑(详情)下的视频列表
    public function getAlbumVideoList()
    {
        $user = $this->auth->getUser();//用户信息
        $album_id = $this->request->param('album_id');//视频专辑id
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);

        //专辑名字+封面+专辑收藏+专辑评价+课程介绍+课程评分+视频id+视频名
        $album_model = AlbumModel::where('id', $album_id)->where('table_name', 'video_category')->field('id,name,introduction,lecturer_introduction,cover_image,membership_price,category_id,average_score')->find();
        if (!$album_model) {
            $this->error('专辑不存在');
        }

        //检测用户是否有权访问内容
        $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'album', $album_model['id'], $album_model['category_id']);
        if ($hasMembershipExpiryRecord['code'] != 200) {
            //尚未购买专辑
            $this->error($hasMembershipExpiryRecord['msg']);
        }

        $album = $album_model->toArray();

        $album['cover_image'] = obsurl($album['cover_image']);
        $album['average_score'] = $album['average_score'] > 5 ? 5:$album['average_score'];//平均分最多5分
        //专辑收藏
        $is_favorite = UserFavorite::where('user_id', $user['id'])
                ->where('table_name', 'album')
                ->where('object_id', $album_id)->value('id') ?? 0;
        $album['is_favorite'] = ($is_favorite > 0 ? 1 : 0);//是否收藏|0否,1是

        $video = \app\admin\model\cms\Video::where('album_id', $album['id'])->order('sort', 'desc')->order('id','desc')->paginate($limit, false, ['page' => $page])->toArray();

        $video_ids = [];
        foreach ($video['data'] as &$v){
            $v['is_favorite'] = 0;//是否点赞收藏
            $video_ids[] = $v['id'];
            //检测用户是否有权访问内容
            $v['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $v['id'], $v['video_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $v['is_member_expire'] = 1;//用户没付钱,弹窗提示
            }


            //视频评分
            $v['rating'] = RatingModel::where('table_name', 'video')
                    ->where('object_id', $v['id'])
                    ->where('user_id', $user['id'])
                    ->value('score') ?? 0;
        }

        //判断视频是否收藏点赞
        if ($video_ids){
            $video_ids = implode(',',$video_ids);
            $favorite_video_id = UserFavorite::where('user_id', $user['id'])
                ->where('table_name', 'video')
                ->whereIn('object_id', $video_ids)
                ->column('object_id');
            foreach ($video['data'] as &$v){
                if (in_array($v['id'],$favorite_video_id)){
                    $v['is_favorite'] = 1;//是否点赞收藏
                }
            }
        }

        $res = [
            'album' => $album,
            'video_list' => $video['data'],
            'total' => $video['total'],
            'current_page' => $video['current_page'],//当前视频页码
        ];
        $this->success('', $res);
    }


}
